package com.photoprint;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * @author Administrator
 *
 */
public class PhotoActivity extends BaseActivity implements OnItemClickListener{
	static final int CROP_DONE = 2;
	static final int SHOW_PROGRESS = 0;
	static final int FINISH = 1;
	
	private int gridView_Item_Width = 0;
	private int gridView_Item_Height = 0;
	
	private boolean mDoLaunch = true;
	private android.app.ProgressDialog mProgressDialog = null;
	
	private File mTempFile;
	
	private DisplayMetrics dm = null;
	
	private TextView tvAlarmmsg;
	private GridView gridView;
	private MyAdapter myAdapter;
	private Cursor thumbCursor;
	private Cursor imageCursor;
	private ArrayList<Photo> thumbnailsDataList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_activity);
        
        init();
	}
	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		if(dm == null){
			dm = new DisplayMetrics();   
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			gridView_Item_Width = (dm.widthPixels-20)/2;
			gridView_Item_Height = gridView_Item_Width;
		}
		
		myAdapter.notifyDataSetChanged();
		
		Log.e("wuyiqi", "myAdapter : "+myAdapter.hashCode());
		
		if(thumbnailsDataList.size()<=0){
			tvAlarmmsg.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(thumbCursor != null){
			thumbCursor.close();
			thumbCursor = null;
		}
		if(imageCursor != null){
			imageCursor.close();
			imageCursor = null;
		}
	}
	
	public void init(){
		initData();
		myAdapter = new MyAdapter();
		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setOnItemClickListener(this);
		gridView.setAdapter(myAdapter);
		
		tvAlarmmsg = (TextView) findViewById(R.id.tv_alarmmsg);
	}
	
	public void initData(){
		if(thumbCursor == null){
			thumbCursor = this.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
					new String[]{MediaStore.Images.Thumbnails.DATA,MediaStore.Images.Thumbnails.IMAGE_ID}, null, null, null);
		}else{
			thumbCursor.requery();
		}
		
		if(thumbnailsDataList == null){
			thumbnailsDataList = new ArrayList<Photo> ();
		}else{
			thumbnailsDataList.clear();
		}
		
		if(thumbCursor.moveToFirst()){
			do{
				Photo photo = new Photo();
				photo.setThumb_data(thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA)));
				photo.setImage_id(thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID)));
				//图片的绝对地址
				imageCursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						new String[]{MediaStore.Images.Media.DATA}, MediaStore.Images.Media._ID+"="+photo.getImage_id(), null, null);
				if(imageCursor != null && imageCursor.moveToFirst()){
					photo.setImage_data(imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA)));
					Log.e("initData", photo.getImage_data());
				}
				imageCursor.close();
				imageCursor = null;
				thumbnailsDataList.add(photo);
			}while(thumbCursor.moveToNext());
		}
	}
	
	
	private final android.os.Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case SHOW_PROGRESS: {
                CharSequence c = getText(R.string.wallpaper);
                mProgressDialog = android.app.ProgressDialog.show(PhotoActivity.this, "", c, true, false);
                break;
            }
            case FINISH: {
                closeProgressDialog();
                setResult(RESULT_OK);
                finish();
                break;
            }
            }
        }
    };

    private synchronized void closeProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == CROP_DONE && (resultCode == RESULT_OK) && (data != null)) {
			initData();
			myAdapter.notifyDataSetChanged();
//			Log.e("wuyiqi", "myAdapter 2 : "+myAdapter.hashCode());
//            try {
//                InputStream s = new FileInputStream(mTempFile);
//                Log.e("wuyiqi", mTempFile.getAbsolutePath());
////                OutputStream o = new FileOutputStream();
//                try {
//                    Bitmap bitmap = BitmapFactory.decodeStream(s);
//                    if (bitmap == null) {
//                        Log.e("PhotoActivity", "Failed to set wallpaper. " + "Couldn't get bitmap for path " + mTempFile);
//                    } else {
////                        mHandler.sendEmptyMessage(SHOW_PROGRESS);
////                        new SetWallpaperThread(bitmap, mHandler, this, mTempFile).start();
//                    	// TODO updata photo
//                    	
//                    }
//                    mDoLaunch = false;
//                } finally {
//                    Util.closeSilently(s);
//                }
//            } catch (FileNotFoundException ex) {
////                Log.e(LOG_TAG, "file not found: " + mTempFile, ex);
//            }
        } else {
//            setResult(RESULT_CANCELED);
//            finish();
        }
    }

	class SetWallpaperThread extends Thread {
	    private final Bitmap mBitmap;
	    private final android.os.Handler mHandler;
	    private final android.content.Context mContext;
	    private final File mFile;
	
	    public SetWallpaperThread(Bitmap bitmap, android.os.Handler handler, android.content.Context context, File file) {
	        mBitmap = bitmap;
	        mHandler = handler;
	        mContext = context;
	        mFile = file;
	    }
	
	    @Override
	    public void run() {
	        try {
	            mContext.setWallpaper(mBitmap);
	        } catch (IOException e) {
//	            Log.e(LOG_TAG, "Failed to set wallpaper.", e);
	        } finally {
	            mHandler.sendEmptyMessage(FINISH);
	            mFile.delete();
	        }
	    }
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Uri uri = Uri.parse("content://media/external/images/media/" + thumbnailsDataList.get(arg2).getImage_id());
		
//		Intent intent = new Intent();
//        intent.setClass(this, CropImage.class);
//        intent.setData(uri);
//        formatIntent(intent);
//        startActivityForResult(intent, CROP_DONE);
		Intent i = new Intent();
		i.setClass(this, PhotoPreviewActivity.class);
		i.putExtra("num", arg2);
		startActivity(i);
	}
	
	protected void formatIntent(Intent intent) {
        // TODO: A temporary file is NOT necessary
        // The CropImage intent should be able to set the wallpaper directly
        // without writing to a file, which we then need to read here to write
        // it again as the final wallpaper, this is silly
        mTempFile = getFileStreamPath("temp-wallpaper");
        mTempFile.getParentFile().mkdirs();

        int width = getWallpaperDesiredMinimumWidth();
        int height = getWallpaperDesiredMinimumHeight();
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", height);
        intent.putExtra("aspectX", width);
        intent.putExtra("aspectY", height);
        intent.putExtra("scale", true);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
        // TODO: we should have an extra called "setWallpaper" to ask CropImage
        // to set the cropped image as a wallpaper directly. This means the
        // SetWallpaperThread should be moved out of this class to CropImage
    }
	
	class MyAdapter extends BaseAdapter  {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return thumbnailsDataList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
//			Uri uri = Uri.parse("file://"+thumbnailsDataList.get(position));
			ImageView iv = null;
			if(convertView == null){
				iv = new ImageView(PhotoActivity.this);
			}else{
				iv = ((ImageView)convertView);
			}
			Bitmap b = BitmapFactory.decodeFile(thumbnailsDataList.get(position).getThumb_data());
			iv.setBackgroundColor(Color.WHITE);
			iv.setPadding(10, 10, 10, 10);
			iv.setImageBitmap(b);
			iv.setScaleType(ImageView.ScaleType.CENTER);
			iv.setLayoutParams(new GridView.LayoutParams(gridView_Item_Width, gridView_Item_Height));
			return iv;
		}
		
	}
}
